package com.analysis.service.impl;

import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.analysis.common.CalculationUtil;
import com.analysis.common.FileUtil;
import com.analysis.model.KLine;
import com.analysis.model.OLS;
import com.analysis.service.KLineService;
import com.analysis.service.KlineLibrary;

@Service
public class KlineLibraryService implements KlineLibrary {
	  private DataSetServiceImpl dataSetService = new DataSetServiceImpl();
	  private KLineService klineService = new KLineServiceImpl();
	  private OLSServiceImpl ols = new OLSServiceImpl ();
	  
	  public static void main(String[] args) {
		  new KlineLibraryService().generateSegmentation("1bf17");
	}
	  
	  public void generateSegmentation(String dataSet) {
		  File file = Paths.get("./kline/libary.txt").toFile();
		  List<String> symbols = new ArrayList<>();
		  
		  if(StringUtils.isNotEmpty(dataSet)) {
			  symbols = dataSetService.getSpecificDataSet(dataSet);
		  }else {
			  try {
				symbols = klineService.getLatestSymbols();
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		  }
		  
		 
		  List<Double> xAxis = getXAxis();
		  double[] xAxisStander = CalculationUtil.standardize(xAxis);
		  
		  int num = 20;
		  for(String symbol:symbols) {
			  List<KLine> klines = klineService.getKline(symbol);
			  System.out.println("Kline Library:"+symbol);
			  for (int i = 0; i + num < klines.size() + 1; i += 5) {
	                List<KLine> subKline = klines.subList(i, i + num);
	                KLine first = subKline.get(0);
	                KLine last = subKline.get(subKline.size()-1);
	                List<Double> yAxis = ols.toDouble(subKline);
	                OLS olsParam = ols.calculatOLS(yAxis, xAxis);
	                double[] yAxiStander = CalculationUtil.standardize(CalculationUtil.toDouble(subKline));
	                double distance = calDistance(xAxisStander, yAxiStander);
	                String data = String.format("%s,%s,%s,%s,%s,%s"
	                		,symbol
	                		,first.getDay().toString()
	                		,last.getDay().toString()
	                		,olsParam.getR_squared()
	                		,olsParam.getRxy()
	                		,distance);
	                FileUtil.writeLine(file, data);
	            }
		  }
	  }
	  
	  public List<Double> getXAxis(){
		  List<Double> xAxis = new ArrayList<>();
		  for(double i=1;i<=20;i++) {
			  xAxis.add(i);
		  }
		  return xAxis;
	  }
	  
	  public double calDistance(double[] x ,double[] y) {
		  double distance = 0;
		  for(int i=0;i<x.length;i++) {
			  distance += (x[i]+y[i]);
		  }
		  return distance;
	  }
}
